package com.kly.chatter.api.application.controller.chatter;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.kly.chatter.api.application.controller.chatter.res.ChatterGreetingRes;
import com.kly.chatter.api.application.service.BaseService;
import com.kly.sc.api.application.enums.ApiResultStatus;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.user.chatterService.GreetingService;
import com.kly.user.chatterService.ModelService;
import com.kly.user.dto.chatter.response.UserChatterModeDto;
import com.kly.user.dto.chatter.response.UserGreetingContentDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Api(value = "招呼语", tags = {"招呼语"})
@RestController
@RequestMapping("/chat/greeting")
public class GreetingController {

    @NacosValue(value = "${chatter.api.greetingMaxNum:5}", autoRefreshed = true)
    private Integer maxNum;

    @Resource
    GreetingService greetingService;

    @Resource
    private BaseService baseService;

    @Resource
    ModelService modelService;

//    @ResponseBody
//    @RequestMapping(value = "/list")
//    public Response queryByModelUserCode(@RequestBody UserGreetingContentDto greetingContentDto) {
//        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
//        Map<String, UserChatterModeDto> modeMap = baseService.getModeMap(userCode);
//        Set<String> keySet = modeMap.keySet();
//        Response<List<UserGreetingContentDto>> listResponse;
//        if (!keySet.isEmpty()) {
//            listResponse = greetingService.queryByModelUserCodes(new ArrayList<>(keySet));
//        }
//        listResponse =
//                greetingService.queryByModelUserCode(greetingContentDto.getModelUserCode());
//        if (listResponse.isSuccess() && listResponse.getData() != null) {
//            ChatterGreetingRes chatterGreeting = new ChatterGreetingRes();
//            chatterGreeting.setModelUserCode(greetingContentDto.getModelUserCode());
//            chatterGreeting.setGreetingList(listResponse.getData());
//            chatterGreeting.setMaxNum(maxNum);
//            return Response.ok(chatterGreeting);
//        }
//        return Response.error();
//    }

    /**
     * 查询招呼语列表1
     * @param greetingContentDto
     * @return
     */
    @ApiOperation("招呼语列表")
    @ResponseBody
    @RequestMapping(value = "/list", method = {RequestMethod.POST})
    @SentinelResource
    public Response queryByModelUserCode(@RequestBody UserGreetingContentDto greetingContentDto) {
        Response<List<UserGreetingContentDto>> listResponse;
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        Map<String, UserChatterModeDto> modeMap = baseService.getModeMap(userCode);
        if (StringUtils.isNotEmpty(greetingContentDto.getModelUserCode())) {
            if (!modeMap.containsKey(greetingContentDto.getModelUserCode())){
                return Response.error(ApiResultStatus.NO_CORRESPONDING_MODE_CODE);
            }
            listResponse = greetingService.queryByModelUserCode(greetingContentDto.getModelUserCode());
        } else {
            if (CollectionUtils.isNotEmpty(modeMap)) {
                Set<String> keySet = modeMap.keySet();
                listResponse = greetingService.queryByModelUserCodes(new ArrayList<>(keySet));
            } else {
                return Response.error(ApiResultStatus.NO_CORRESPONDING_MODE_CODE);
            }
        }
        Map<String, List<UserGreetingContentDto>> groupedByModelUserCode =new HashMap<>();
        List<ChatterGreetingRes> result = new ArrayList<>();
        if (listResponse.isSuccess() && CollUtil.isNotEmpty(listResponse.getData())) {
            groupedByModelUserCode= listResponse.getData().stream()
                    .collect(Collectors.groupingBy(UserGreetingContentDto::getModelUserCode));
            for (Map.Entry<String, List<UserGreetingContentDto>> entry : groupedByModelUserCode.entrySet()) {
                ChatterGreetingRes chatterGreetingRes = new ChatterGreetingRes();
                chatterGreetingRes.setModelUserCode(entry.getKey());
                chatterGreetingRes.setGreetingList(entry.getValue());
                chatterGreetingRes.setMaxNum(maxNum);
                UserChatterModeDto userChatterModeDto = modeMap.get(entry.getKey());
                chatterGreetingRes.setModelName(userChatterModeDto.getModelNickName());
                chatterGreetingRes.setModelAvatarUrl(userChatterModeDto.getModelAvatarUrl());
                result.add(chatterGreetingRes);
            }
        }else if (StringUtils.isNotEmpty(greetingContentDto.getModelUserCode())&&CollUtil.isEmpty(listResponse.getData())){
            ChatterGreetingRes chatterGreetingRes = new ChatterGreetingRes();
            chatterGreetingRes.setModelUserCode(greetingContentDto.getModelUserCode());
            chatterGreetingRes.setGreetingList(new ArrayList<>());
            chatterGreetingRes.setMaxNum(maxNum);
            UserChatterModeDto userChatterModeDto = modeMap.get(greetingContentDto.getModelUserCode());
            chatterGreetingRes.setModelName(userChatterModeDto.getModelNickName());
            chatterGreetingRes.setModelAvatarUrl(userChatterModeDto.getModelAvatarUrl());
            result.add(chatterGreetingRes);
        }
        if (StringUtils.isEmpty(greetingContentDto.getModelUserCode())){
            for (String key : modeMap.keySet()) {
                if (!groupedByModelUserCode.containsKey(key)) {
                    ChatterGreetingRes chatterGreetingRes = new ChatterGreetingRes();
                    chatterGreetingRes.setModelUserCode(key);
                    chatterGreetingRes.setGreetingList(new ArrayList<>());
                    chatterGreetingRes.setMaxNum(maxNum);
                    UserChatterModeDto userChatterModeDto = modeMap.get(key);
                    chatterGreetingRes.setModelName(userChatterModeDto.getModelNickName());
                    chatterGreetingRes.setModelAvatarUrl(userChatterModeDto.getModelAvatarUrl());
                    result.add(chatterGreetingRes);
                }
            }
        }

        return Response.ok(result);
    }

    @ApiOperation("招呼语修改")
    @ResponseBody
    @RequestMapping(value = "/modify", method = {RequestMethod.POST})
    @SentinelResource
    public Response updateGreeting(@RequestBody UserGreetingContentDto greetingContentDto) {
        if (StringUtils.isEmpty(greetingContentDto.getGreetingCode())
                ||StringUtils.isEmpty(greetingContentDto.getGreetingContent())){
            return Response.error(ApiResultStatus.PARAMETER_EMPTY);
        }
        return greetingService.updateGreeting(greetingContentDto);
    }

    /**
     * 添加招呼语
     * @param greetingContentDto
     * @return
     */
    @ApiOperation("添加招呼语")
    @ResponseBody
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @SentinelResource
    public Response saveGreeting(@RequestBody UserGreetingContentDto greetingContentDto) {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        Map<String, UserChatterModeDto> modeMap = baseService.getModeMap(userCode);

        if (modeMap.isEmpty()
                ||modeMap.get(greetingContentDto.getModelUserCode())==null
                ||StringUtils.isEmpty(greetingContentDto.getModelUserCode())
                ||StringUtils.isEmpty(greetingContentDto.getGreetingContent())){
            Response.error(ApiResultStatus.PARAMETER_VALIDATION_FAILED);
        }
        Response<List<UserGreetingContentDto>> listResponse =
                greetingService.queryByModelUserCode(greetingContentDto.getModelUserCode());
        if (listResponse.isSuccess() && listResponse.getData() != null && listResponse.getData().size() > maxNum) {
            final List<UserGreetingContentDto> userGreetingContentDtos = listResponse.getData();
            final long approvalPassNum = userGreetingContentDtos.parallelStream().filter(o -> o.getStatus() == 0 || o.getStatus() == 1 || o.getStatus() == 2).count();
            if (approvalPassNum > maxNum) {
                return Response.error(ApiResultStatus.GREETINGS_LIMIT_REACHED);
            }
        }
        return greetingService.saveGreeting(greetingContentDto);
    }

    @ApiOperation("删除招呼语")
    @ResponseBody
    @RequestMapping(value = "/remove", method = {RequestMethod.POST})
    @SentinelResource
    public Response delGreeting(@RequestBody UserGreetingContentDto greetingContentDto) {
        return greetingService.delGreeting(greetingContentDto);
    }
}
